package cn.minhx.domain.strategy.service.armory;

import cn.minhx.domain.strategy.model.entity.StrategyAwardEntity;
import cn.minhx.domain.strategy.model.entity.StrategyEntity;
import cn.minhx.domain.strategy.model.entity.StrategyRuleEntity;
import cn.minhx.domain.strategy.repository.IStrategyRepository;
import cn.minhx.types.common.Constants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.*;

import static cn.minhx.types.enums.ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL;
import static cn.minhx.types.exception.AppException.exception;

/**
 * 策略装配，负责初始化策略计算
 *
 * @author min
 */
@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository repository;

    @Override
    public Boolean assembleLotteryStrategy(Long strategyId) {
        // 1. 默认抽奖装配
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);
        //  缓存此策略奖品库存【用于decr扣减库存】
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Long awardId = strategyAward.getAwardId();
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        // 2. 权重抽奖装配 - 适用于 rule_weight 权重规则配置
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if (null == ruleWeight) {
            return true;
        }
        // 获取rule
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        if (null == strategyRuleEntity) {
            throw exception(STRATEGY_RULE_WEIGHT_IS_NULL);
        }
        Map<String, List<Long>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        ruleWeightValueMap.forEach((key, ruleWeightValues) -> {
            List<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        });
        return true;
    }

    @Override
    public Long getRandomAwardId(Long strategyId) {
        // 1. 获取概率范围
        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        int rateRange = repository.getRateRange(strategyId);
        // 2. 通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Long getRandomAwardId(Long strategyId, String ruleWeightValue) {
        // 1. 获取概率范围
        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        int rateRange = repository.getRateRange(Constants.RedisKey.STRATEGY_RATE_RANGE_KEY + key);
        // 2. 通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Boolean subtractAwardStock(Long strategyId, Long awardId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractAwardStock(cacheKey);
    }

    /**
     * 缓存奖品库存到Redis
     *
     * @param strategyId 策略ID
     * @param awardId    奖品ID
     * @param awardCount 奖品库存
     */
    private void cacheStrategyAwardCount(Long strategyId, Long awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 1. 获取最小概率值
        BigDecimal minAwardRate = getMinAwardRate(strategyAwardEntities);
        // 2. 获得概率范围，百分位、千分位、万分位
        BigDecimal rateRange = getRateRange(minAwardRate);
        // 3. 生成策略奖品概率查找表
        //  先放list中是为了先对奖品和对应的下标(抽中的随机数)进行乱序
        List<Long> awardSerchList = getAwardSerchList(rateRange, strategyAwardEntities);
        // 4. 乱序
        Collections.shuffle(awardSerchList);
        // 5. 生成Map集合，
        Map<Integer, Long> shuffledAwardSearchTable = getShuffledAwardSearchTable(awardSerchList);
        // 6. 存到 Redis 中
        repository.storeStrategyAwardSearchRateTable(key, shuffledAwardSearchTable.size(), shuffledAwardSearchTable);
    }

    private static Map<Integer, Long> getShuffledAwardSearchTable(List<Long> awardSerchList) {
        Map<Integer, Long> shuffledAwardSearchTable = new LinkedHashMap<>();
        for (int i = 0; i < awardSerchList.size(); i++) {
            Long awardId = awardSerchList.get(i);
            shuffledAwardSearchTable.put(i, awardId);
        }
        return shuffledAwardSearchTable;
    }


    private static List<Long> getAwardSerchList(BigDecimal rateRange, List<StrategyAwardEntity> strategyAwardEntities) {
        // 「这里指需要在list集合中，存放上对应的奖品占位即可，占位越多等于概率越高，下标为概率，list[i]为奖品」
        List<Long> awardSerchList = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Long awardId = strategyAwardEntity.getAwardId();
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            // 计算出每个概率需要存放到查找表的数量，并进行填充
            // rateRange.multiply(awardRate) 一定是整数，不用取整
            int num = rateRange.multiply(awardRate).intValue();
            for (int i = 0; i < num; i++) {
                awardSerchList.add(awardId);
            }
        }
        return awardSerchList;
    }

    private static BigDecimal getMinAwardRate(List<StrategyAwardEntity> strategyAwardEntities) {
        return strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal::min)
                .orElse(BigDecimal.ZERO);
    }

    /**
     * 获取概率范围，只根据小数位来计算。如【0.01返回100】、【0.009返回1000】、【0.0018返回10000】
     */
    private BigDecimal getRateRange(BigDecimal minAwardRate) {
        if (BigDecimal.ZERO.compareTo(minAwardRate) == 0) {
            return BigDecimal.ONE;
        }
        double current = minAwardRate.doubleValue();
        int max = 1;
        while (current < 1) {
            current = current * 10;
            max = max * 10;
        }
        return BigDecimal.valueOf(max);
    }
}
